from django.urls import reverse
from django.utils.safestring import mark_safe

from app01 import models
from stark.service.stark import StarkHandler


class CourseRecordConfig(StarkHandler):
    def display_course(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '上课记录'
        return '%s-s%s-day%s' % (
            obj.class_object.course, str(obj.class_object.semester).rjust(2, '0'), str(obj.day_num).rjust(3, '0'))

    def display_study_record(self, obj=None, is_header=None, *args, **kwargs):
        if is_header:
            return '学习记录'
        tpl = '<a href="%s?cid=%s">学习记录</a>' % (reverse('stark:app01_studyrecord_list'), obj.id)
        return mark_safe(tpl)

    list_display = [display_course, 'teacher', display_study_record, 'date']

    def get_list_display(self, request, *args, **kwargs):
        val = super().get_list_display(request)
        val.insert(0, StarkHandler.display_checkbox)
        return val

    def multi_init(self, request):
        course_list = request.POST.getlist('pk')
        for course_record_id in course_list:
            course_record = models.CourseRecord.objects.filter(id=course_record_id).first()
            for student in models.Student.objects.filter(class_list=course_record.class_object):
                models.StudyRecord.objects.create(course_record_id=course_record_id, student=student)

    multi_init.text = '批量初始化'
    action_list = [multi_init]
